﻿using Microsoft.AspNetCore.Mvc;
using orm.sqlsugar.api.Entities;
using SqlSugar;

namespace orm.sqlsugar.api.Controllers
{
    /// <summary>
    /// 单表操作
    /// </summary>
    public class SingleController(ISqlSugarClient sqlSugarClient) 
        : SqlSugarBaseController(sqlSugarClient)
    {
        [HttpPost]
        public async Task<IActionResult> Insert()
        {
            var order = new Order
            {
                Number = DateTime.Now.ToString("yyyyMMddHHmmss"),
                CreateTime = DateTime.Now
            };

            return Ok("Id：" + await SqlSugarClient
                .Insertable(order)
                .ExecuteReturnIdentityAsync());
        }

        [HttpPatch]
        public async Task<IActionResult> Update(int id)
        {
            var order = new Order
            {
                Id = id,
                Number = DateTime.Now.ToString("yyyyMMddHHmmss"),
                TotalPrice = 1,
                CreateTime = DateTime.Now
            };

            return Ok(await SqlSugarClient
                .Updateable(order)
                .ExecuteCommandAsync() > 0);
        }

        [HttpDelete]
        public async Task<IActionResult> Delete(int id)
        {
            return Ok(await SqlSugarClient
                .Deleteable<Order>()
                .Where(o => o.Id == id)
                .ExecuteCommandAsync() > 0);
        }

        [HttpGet]
        public async Task<IActionResult> PageList(int pageIndex, int pageSize)
        {
            RefAsync<int> totalResult = 0;

            var orders = await SqlSugarClient
                .Queryable<Order>()
                .Where(o => o.IsDeleted == false)
                .OrderByDescending(o => o.Id)
                .ToOffsetPageAsync(pageIndex, pageSize, totalResult);

            return Ok(new { rows = orders, total = totalResult.Value });
        }

        [HttpGet]
        public async Task<IActionResult> Detail(int id)
        {
            return Ok(await SqlSugarClient
                .Queryable<Order>()
                .InSingleAsync(id));
        }
    }
}
